package com.windchime.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.windchime.blog.entity.Blog;
import com.windchime.blog.entity.Tag;
import com.windchime.blog.entity.Type;
import com.windchime.blog.entity.vo.echarts.BarVo;
import com.windchime.blog.entity.vo.echarts.PieVo;
import com.windchime.blog.service.BlogService;
import com.windchime.blog.service.TagService;
import com.windchime.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@Controller
public class FrontArchivesController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping("/archives")
    public String archives(Model model) {
        //所有已发布的文章数量
        model.addAttribute("blogNum", blogService.list(new QueryWrapper<Blog>().eq("published", true)).size());
        //分类数量
        model.addAttribute("typeNum", typeService.list().size());
        //标签数量
        model.addAttribute("tagNum", tagService.list().size());

        //设置年归档
        model.addAttribute("archives", blogService.archiveBlog());
        model.addAttribute("blogCount", blogService.list(new QueryWrapper<Blog>().eq("published", true)).size());
        return "/archives";
    }

    /**
     * 柱状图
     * @return barVo
     */
    @PostMapping("/getBars")
    @ResponseBody
    public BarVo getBars() {
        List<Type> types = typeService.list();
        List<String> typeNames = types.stream().map(Type::getName).collect(Collectors.toList());

        //设置每个分类有多少篇博客
        for (Type type : types) {
            Integer typeHasBlogs = blogService.typeHasBlogsByTypeId(type.getId());
            type.setTypeHasBlogs(typeHasBlogs);
        }

        List<Integer> typeHasBlogs = types.stream().map(Type::getTypeHasBlogs).collect(Collectors.toList());

        BarVo barVo = new BarVo();
        barVo.setNames(typeNames);
        barVo.setValues(typeHasBlogs);

        return barVo;
    }

    /**
     * 饼状图
     * @return pieVos
     */
    @PostMapping("/getPies")
    @ResponseBody
    public List<PieVo> getPies() {
        List<Tag> tags = tagService.list();
        //设置每个标签有多少篇博客
        for (Tag tag : tags) {
            Integer tagHasBlogs = blogService.tagHasBlogsByTagId(tag.getId());
            tag.setTagHasBlogs(tagHasBlogs);
        }
        return tags.stream().map(pieVo -> new PieVo(pieVo.getTagHasBlogs(), pieVo.getName())).collect(Collectors.toList());
    }


}
